package com.tbvtc.agriculturalcreditchainserver2025.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Crop;
import com.tbvtc.agriculturalcreditchainserver2025.entity.CropFertilizerCheck;
import com.tbvtc.agriculturalcreditchainserver2025.entity.PesticideReportResult;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CropFertilizerCheckMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.ICropFertilizerCheckService;
import com.tbvtc.agriculturalcreditchainserver2025.service.ICropService;
import com.tbvtc.agriculturalcreditchainserver2025.service.IpfsService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PesticideReportGenerator;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import com.tbvtc.agriculturalcreditchainserver2025.vo.ConsumerVo.CropFertilizerCheckItems;
import com.tbvtc.agriculturalcreditchainserver2025.vo.ConsumerVo.CropFertilizerCheckVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.ConsumerVo.GetDetectionReportVo;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 农作物施肥用量核查表（含标准/农户用量、合格判断及AI建议） 服务实现类
 * </p>
 *
 * @author syh
 * @since 2025-10-05
 */
@Service
public class CropFertilizerCheckServiceImpl extends ServiceImpl<CropFertilizerCheckMapper, CropFertilizerCheck> implements ICropFertilizerCheckService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ICropService cropService;
    @Resource
    private PesticideReportGenerator pesticideReportGenerator;
    @Resource
    private IpfsService ipfsService;
    @Resource
    private RestTemplate restTemplate;


    @Override
    public Result getDetectionReport(String cropId) {
        GetDetectionReportVo detectionReportVo = new GetDetectionReportVo();
        List<GetDetectionReportVo> cropFertilizerCheckVos = new ArrayList<>();
        Crop crop = cropService.getById(cropId);
        String hash = stringRedisTemplate.opsForValue().get("pesticideReport:" + cropId);
        if (hash == null) {
            return RUtils.Err(0, "数据不存在");
        }
        detectionReportVo.setCropName(crop.getName());
        detectionReportVo.setStageType("成熟期");
        detectionReportVo.setCropFertilizerCheckItems(hash);
        cropFertilizerCheckVos.add(detectionReportVo);
        return RUtils.success(cropFertilizerCheckVos);
    }

    @Override
    public Result test(Integer id) {
        Crop crop = cropService.getById(id);
        List<CropFertilizerCheck> cropFertilizerChecks = list(new LambdaQueryWrapper<CropFertilizerCheck>()
                .eq(CropFertilizerCheck::getCropName, crop.getName())
        );
        List<CropFertilizerCheckVo> cropFertilizerCheckVos = new ArrayList<>();
        Map<String, List<CropFertilizerCheck>> collect = cropFertilizerChecks.stream().collect(Collectors.groupingBy(CropFertilizerCheck::getStageType));
        collect.entrySet().forEach(entry -> {
            CropFertilizerCheckVo cropFertilizerCheckVo = new CropFertilizerCheckVo();
            cropFertilizerCheckVo.setStageType(entry.getKey());
            cropFertilizerCheckVo.setCropName(crop.getName());
            List<CropFertilizerCheckItems> cropFertilizerCheckItems = BeanUtil.copyToList(entry.getValue(), CropFertilizerCheckItems.class);
            cropFertilizerCheckVo.setCropFertilizerCheckItems(cropFertilizerCheckItems);
            cropFertilizerCheckVo.setIsQualified(true);
            cropFertilizerCheckItems.stream().forEach(cropFertilizerCheckItem -> {
                if (!cropFertilizerCheckItem.getIsQualified()) {
                    cropFertilizerCheckVo.setIsQualified(false);
                }
            });
//            cropFertilizerCheckVo.setCropFertilizerCheckItems("QmYGEKk7LEt3xdUHzudxY88yh2yVZztUwH3EC2bhsH8Jbm");
            cropFertilizerCheckVos.add(cropFertilizerCheckVo);
        });
        pesticideReportGenerator.generateReport(cropFertilizerCheckVos, "C:\\Users\\syh05\\Desktop\\新建文件夹\\pesticide_report.html");
        File file = new File("C:\\Users\\syh05\\Desktop\\新建文件夹\\pesticide_report.html");
//        String hash = "";
//        WebClient webClient = WebClient.create();
//        MultipartBodyBuilder builder = new MultipartBodyBuilder();
//        builder.part("html_file", new FileSystemResource(file)); // 添加文件部分
//        Mono<PesticideReportResult> pesticideReportResultMono = webClient.post()
//                .uri("http://localhost:8000/html2img")
//                .contentType(MediaType.MULTIPART_FORM_DATA)
//                .body(BodyInserters.fromMultipartData(builder.build()))
//                .retrieve()
//                .bodyToMono(PesticideReportResult.class);
//        pesticideReportResultMono.subscribe(pesticideReportResult -> {
//            try {
//                byte[] bytes = Base64.getDecoder().decode(pesticideReportResult.getBase64());
//                String hash = ipfsService.uploadToIpfs(bytes);
//            } catch (IOException e) {
//                System.out.println(e.getMessage());
//                throw new RuntimeException(e);
//            }
//
//        });

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

// 2. 构建form-data的请求体，将文件包装为FileSystemResource
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("html_file", new FileSystemResource(file)); // 注意参数名要和后端接口的接收参数名（html_file）一致

// 3. 封装请求实体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        PesticideReportResult pesticideReportResult = restTemplate.postForObject("http://localhost:8000/html2img",
                requestEntity, PesticideReportResult.class);
        try {
            byte[] bytes = Base64.getDecoder().decode(pesticideReportResult.getBase64());
            String hash = ipfsService.uploadToIpfs(bytes);
            return RUtils.success(hash);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
